package com.github.florent37.rxretrojsoup.tutosohosfrance.slice;

import com.github.florent37.retrojsoup.RetroJsoup;
import com.github.florent37.rxretrojsoup.ResourceTable;
import com.github.florent37.rxretrojsoup.rxoh.schedulers.OhosSchedulers;
import com.github.florent37.rxretrojsoup.tutosohosfrance.Article;
import com.github.florent37.rxretrojsoup.tutosohosfrance.ListItemProvider;
import com.github.florent37.rxretrojsoup.tutosohosfrance.TutoOhosFrance;
import io.reactivex.schedulers.Schedulers;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.ListContainer;
import okhttp3.OkHttpClient;

import java.util.List;


public class MainAbilitySlice extends AbilitySlice {

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        loadWithRetroJsoup();
    }

    private void loadWithRetroJsoup() {

        final OkHttpClient okHttpClient = new OkHttpClient();

        final TutoOhosFrance tutosOhosFrance = new RetroJsoup.Builder()
                .url("https://www.html5tricks.com/category/html5-demo")
                .client(okHttpClient)
                .build()
                .create(TutoOhosFrance.class);

        tutosOhosFrance.articles()
                .toList()
                .subscribeOn(Schedulers.newThread())
                .observeOn(OhosSchedulers.mainThread())
                .subscribe(t -> initListContainer(t));
    }

    private void initListContainer(List<Article> items) {
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_container);
        ListItemProvider sampleItemProvider = new ListItemProvider(items, this);
        listContainer.setItemProvider(sampleItemProvider);
    }


}
